package main

import (
	"log"
	"os"

	"github.com/go-yaml/yaml"
)

type AppParam struct {
	Enabled bool
	Addr    string
	VlanId  int
	VlanPri int
	AppId   uint32
}

type Config struct {
	IFace    string
	GooseSub AppParam
	GoosePub AppParam
	SvSub    AppParam
}

const ConfigFile = "config.yaml"

func LoadConfig() *Config {
	cfg := Config{}

	fin, err := os.Open(ConfigFile)
	defer fin.Close()
	if err != nil {
		log.Println(ConfigFile, err)
		return nil
	}
	buf := make([]byte, 1024)
	n := 0
	for {
		count, _ := fin.Read(buf[n:])
		n += count
		if 0 == count {
			break
		}
	}
	err = yaml.Unmarshal(buf[:n], &cfg)
	if err != nil {
		log.Fatalf("error: %v", err)
		return nil
	}
	return &cfg
	//fmt.Printf("--- cfg:\n%v\n\n", cfg)
}

func (cfg *Config) Save() bool {
	buf, err := yaml.Marshal(&cfg)
	if err != nil {
		log.Fatalf("error: %v", err)
		return false
	}

	fout, err := os.Create(ConfigFile)
	defer fout.Close()
	if err != nil {
		log.Println(ConfigFile, err)
		return false
	}
	fout.Write(buf)
	return true
}
